package com.fc.converters;

import javax.faces.bean.ApplicationScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import com.fc.entities.UnitOfMeasurement;
import com.fc.service.UnitOfMeasurementService;
import com.fc.utils.ServiceLocator;

/**
 * 
 * @author aacs
 * 
 */
@Component("unitOfMeasurementConverter")
@ApplicationScoped
public class UnitOfMeasurementConverter implements Converter {
	private UnitOfMeasurementService service;

	public UnitOfMeasurementService getService() {
		if (service == null) {
			service = ServiceLocator.getBean(UnitOfMeasurementService.class);
		}
		return service;
	}

	@Override
	public UnitOfMeasurement getAsObject(FacesContext context,
			UIComponent component, String value) {
		if (StringUtils.isBlank(value)) {
			return null;
		}

		return getService().findByName(value);
	}

	@Override
	public String getAsString(FacesContext context, UIComponent component,
			Object value) {
		if (value == null || !(value instanceof UnitOfMeasurement)) {
			return "";
		}
		UnitOfMeasurement unitOfMeasurement = (UnitOfMeasurement) value;
		return unitOfMeasurement.getName();
	}
}
